<?php

namespace app\index\controller;

use mikkle\tp_wxpay\JsApi_pub;
use mikkle\tp_wxpay\UnifiedOrder_pub;
use WxPay;

class Pay extends Common
{
    /**
     * 支付页面
     */
    public function index()
    {
        return $this->fetch();
    }

    public function payOrder()
    {

        $res = db("order");
        //获取订单号
        $where['order_sn'] = input('post.order_sn');
        $orderSn = input('post.order_sn');
        //查询订单信息
        $order_info = $res->where($where)->find();
        //获取支付方式
        $pay_type = input('post.pay_type');//微信支付 或者支付宝支付
        //获取支付金额
        $money = $order_info['total_amount'];
        if ($pay_type == "") {
            $this->rest("请选择支付方式", "s004");
        }
        if (!$order_info) {
            $this->rest("没有找到订单", "s004");
        }
        //判断支付方式
        switch ($pay_type) {
            case 'ali'://如果支付方式为支付宝支付
                $this->rest("暂未接入支付宝支付", "s004");
                break;
            case 'wx':
                $wx = new Wxpay();//实例化微信支付控制器
                $body = '订单号' . $orderSn;//支付说明
                $out_trade_no = $orderSn;//订单号
                $total_fee = $money * 100;//支付金额(乘以100)
                $notify_url = "http://api.huaxiaoujia.com/index/notify/wxPayCallBackUrl";//回调地址
                $order = $wx->getPrePayOrder($body, $out_trade_no, $total_fee, $notify_url);//调用微信支付的方法
                if ($order['prepay_id']) {//判断返回参数中是否有prepay_id

                    $order1 = $wx->getOrder($order['prepay_id']);//执行二次签名返回参数

                    echo $this->rest(array('status' => 1, 'prepay_order' => $order1));
                } else {
                    echo $this->rest(array('status' => 0, 'msg' => $order['err_code_des']));
                }
                break;
            case 'native':
                $wx = new Wxpay();//实例化微信支付控制器
                $body = '订单号' . $orderSn;//支付说明
                $out_trade_no = $orderSn;//订单号
                $total_fee = $money * 100;//支付金额(乘以100)
                $notify_url = "http://api.huaxiaoujia.com/index/notify/wxPayCallBackUrl";//回调地址
                $order = $wx->getNativePayOrder($body, $out_trade_no, $total_fee, $notify_url);//调用微信支付的方法
                $qrImage = getQrPng($order["code_url"]);
                $this->rest(["qrImage" => $qrImage]);
                break;
            default:
                $this->rest("请选择支付方式", "s004");
                break;
        }
    }


    /**
     * 微信支付回调数据
     */
    public function wxPayCallBack()
    {
        if (input('user_id') && input('post.act_id')) {
            $data = [
                'open_id' => db('users')->find(input('user_id'))['openid'],
                'order_no' => date('YmdHis') . rand(1000, 9999),
                'amount' => \input('post.price', 1),
            ];
            //创建订单数据
            createOrder($data['order_no'], $data['amount'], $data['open_id'], \input('post.act_id'));
            //统一下单
            $unified_order = $this->unifiedOrder($data);
            return $this->getParameters($unified_order);
        }
    }

    /**
     * 获取JsApi$getParameters参数
     * #User: Mikkle
     * #Email:776329498@qq.com
     * #Date:
     * @param string $unified_order
     * @return string
     */
    protected function getParameters($unified_order = '')
    {
        $jsApi = new JsApi_pub();
        $jsApi->setPrepayId($unified_order);
        $jsApiParameters = $jsApi->getParameters();
        return $jsApiParameters;
    }

    /**
     * 统一下单方法
     * #User: Mikkle
     * #Email:776329498@qq.com
     * #Date:
     * @param array $data
     * @return bool
     */
    protected function unifiedOrder($data = [])
    {
        $unifiedOrder = new UnifiedOrder_pub();
        $unifiedOrder->setParameter("openid", $data['open_id']); // openid
        $unifiedOrder->setParameter("body", '商品订单号' . $data['order_no']); // 商品描术
        $unifiedOrder->setParameter("out_trade_no", $data['order_no']); // 商户订单号. '_' . $unifiedOrder->createNoncestr(6)
        $unifiedOrder->setParameter("total_fee", $data['amount'] * 100); // 总金额
        $unifiedOrder->setParameter("notify_url", "http://smallpage.cn/api.php/index/Notify/wxPayCallBackUrl"); // 通知地址 $this->notify_url自己定义
        $unifiedOrder->setParameter("trade_type", "JSAPI"); // 交易类型
        return $unifiedOrder->getPrepayId();
    }

    public function tryout()
    {
        $id = input('post.act_id');
        if ($id) {
            //获取当前广告信息
            $db = db('advert');
            $act = $db->where('id', $id)->find();
            if ($act['end_time'] == 0) {
                $EndTime = strtotime("+1 day");
                $db->where('id', $id)->setField('end_time', $EndTime);
                $this->success("试用成功");
            } else {
                $this->error("不能再试用");
            }
        } else {
            $this->error("参数错误$id");
        }
    }

}
